<template>
  <form-item-wrapper
    :designer="designer"
    :field="field"
    :rules="rules"
    :design-state="designState"
    :parent-widget="parentWidget"
    :parent-list="parentList"
    :index-of-parent-list="indexOfParentList"
    :sub-form-row-index="subFormRowIndex"
    :sub-form-col-index="subFormColIndex"
    :sub-form-row-id="subFormRowId"
  >
    <el-input
      ref="fieldEditor"
      v-model="fieldModel"
      :disabled="field.options.disabled"
      :readonly="field.options.readonly"
      :size="widgetSize"
      class="hide-spin-button"
      :type="inputType"
      :show-password="field.options.showPassword"
      :placeholder="field.options.placeholder"
      :clearable="field.options.clearable"
      :minlength="field.options.minLength"
      :maxlength="field.options.maxLength"
      :show-word-limit="field.options.showWordLimit"
      :prefix-icon="field.options.prefixIcon"
      :suffix-icon="field.options.suffixIcon"
      @click="openMap"
    >
      <template #append v-if="field.options.appendButton">
        <el-button
          :disabled="field.options.disabled || field.options.appendButtonDisabled"
          @click="emitAppendButtonClick"
          ><svg-icon :icon-class="field.options.buttonIcon"
        /></el-button>
      </template>
    </el-input>
  </form-item-wrapper>
  <el-dialog v-model="mapVisible" :destroy-on-close="true" title="地图选择">
    <div id="map" style="width: 100%; height: 400px"></div>
  </el-dialog>
</template>

<script>
import FormItemWrapper from "@/components/form-designer/form-widget/field-widget/form-item-wrapper.vue";
import emitter from "@/utils/emitter";
import i18n, { translate } from "@/utils/i18n";
import fieldMixin from "@/components/form-designer/form-widget/field-widget/fieldMixin";
import SvgIcon from "@/components/svg-icon/index";
import mapboxgl from "mapbox-gl";
import "mapbox-gl/dist/mapbox-gl.css";
import MapboxLanguage from "@mapbox/mapbox-gl-language";
import { nextTick, ref } from "vue";
export default {
  name: "mapPoint-widget",
  componentName: "FieldWidget", //必须固定为FieldWidget，用于接收父级组件的broadcast事件
  mixins: [emitter, fieldMixin, i18n],
  data() {
    return {
      map: null,
      mapVisible: false,
      oldFieldValue: null, //field组件change之前的值
      fieldModel: null,
      rules: [],
    };
  },
  props: {
    field: Object,
    parentWidget: Object,
    parentList: Array,
    indexOfParentList: Number,
    designer: Object,

    designState: {
      type: Boolean,
      default: false,
    },

    subFormRowIndex: {
      /* 子表单组件行索引，从0开始计数 */ type: Number,
      default: -1,
    },
    subFormColIndex: {
      /* 子表单组件列索引，从0开始计数 */ type: Number,
      default: -1,
    },
    subFormRowId: {
      /* 子表单组件行Id，唯一id且不可变 */ type: String,
      default: "",
    },
  },
  components: {
    FormItemWrapper,
    SvgIcon,
  },
  created() {
    /* 注意：子组件mounted在父组件created之后、父组件mounted之前触发，故子组件mounted需要用到的prop
         需要在父组件created中初始化！！ */
    this.initFieldModel();
    this.registerToRefList();
    this.initEventHandler();
    this.buildFieldRules();

    this.handleOnCreated();
  },

  mounted() {
    this.handleOnMounted();
  },

  beforeUnmount() {
    this.unregisterFromRefList();
  },
  methods: {
    handleCloseCustomEvent() {
      if (!!this.field.options.onClose) {
        let changeFn = new Function(this.field.options.onClose);
        changeFn.call(this);
      }
    },
    openMap() {
      if (this.designState) return;
      this.mapVisible = true;
      nextTick(() => {
        this.initMap();
      });
    },
    inputType() {
      if (this.field.options.type === "number") {
        return "text"; //当input的type设置为number时，如果输入非数字字符，则v-model拿到的值为空字符串，无法实现输入校验！故屏蔽之！！
      }

      return this.field.options.type;
    },
    initMap() {
      // Mapbox初始化
      mapboxgl.accessToken =
        "pk.eyJ1Ijoid29kZjU5MDMzIiwiYSI6ImNtMWk0YTg1MDBpNjkyanNlZDUwZ3ljODYifQ.zJxfW-O84OOmKgzrCB8ZIg"; // 替换为你的Mapbox访问令牌
      this.map = new mapboxgl.Map({
        container: "map", // 容器ID
        style: "mapbox://styles/mapbox/light-v10", // 地图样式
        center: [114.26, 30.58], // 默认坐标
        zoom: 12, // 默认缩放等级
      });
      this.map.addControl(new MapboxLanguage({ defaultLanguage: "zh-Hans" }));
      this.map.getCanvas().style.cursor = "crosshair";
      if (this.fieldModel) {
        const [lng, lat] = this.fieldModel.split(",").map(Number);
        new mapboxgl.Marker()
          .setLngLat([lng, lat]) // 设置标记点的经纬度
          .setPopup(
            new mapboxgl.Popup().setHTML(`<h1>选取点: (${lng}, ${lat})</h1>`)
          ) // 可选，添加弹出框
          .addTo(this.map);
      }
      this.map.on("click", (e) => {
        //先清除之前的标记点
        this.map.removeLayer("marker");
        const lng = e.lngLat.lng;
        const lat = e.lngLat.lat;
        new mapboxgl.Marker()
          .setLngLat([lng, lat]) // 设置标记点的经纬度
          .setPopup(
            new mapboxgl.Popup().setHTML(`<h1>选取点: (${lng}, ${lat})</h1>`)
          ) // 可选，添加弹出框
          .addTo(this.map);
        this.fieldModel = `${lng}, ${lat}`; // 更新坐标
        this.handleChangeEvent(`${lng}, ${lat}`)
        this.map.getCanvas().style.cursor = "";
        this.mapVisible = false;
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "../../../styles/global.scss"; /* form-item-wrapper已引入，还需要重复引入吗？ */
</style>
